// pages/order/order.js
import { request } from "../../request/index.js";
Page({
  /**
   * 页面的初始数据
   */
  data: {
    orders: [],
    tabs: [{
      id: 0,
      value: '全部',
      isActive: true
    },
    {
      id: 1,
      value: '待付款',
      isActive: false
    },
    {
      id: 2,
      value: '待发货',
      isActive: false
    },
    {
      id: 3,
      value: '退款退货',
      isActive: false
    }
    ]
  },

  //根据标题索引来激活选中的标题数组
  changeTitleByIndex(index) {
    // 2.修改原数组
    console.log(this.data);
    let { tabs } = this.data
    //赋值 到data
    tabs.forEach((v, i) => i == index ? v.isActive = true : v.isActive = false);
    this.setData({
      tabs
    })
  },
  //从子组件传过来
  handleTabsItemChange(e) {
    // console.log(e);
    //1.获取点击的索引
    const { index } = e.detail
    this.changeTitleByIndex(index)
    //重新发请求 type=1 index=0 所以发请求加一
    this.getOrders(index + 1)
  },
  onShow() {
    //判断缓存中有没有token
    // console.log(this.data.address.all);
    const token = wx.getStorageSync('token')
    //判断
    if (!token) {
      wx.navigateTo({ url: '/pages/auth/auth', });
      return
    };
    //1.获取小程序数组的长度
    let pages = getCurrentPages()
    console.log(pages);
    //2.数组索引最大的就是当前页面
    let currentPage = pages[pages.length - 1]
    // console.log(currentPage.options);
    //获取url的type参数
    const { type } = currentPage.options
    //4.激活选中的页面 当type=1 index=0
    this.changeTitleByIndex(type - 1)
    this.getOrders(type)
  },
  //获取订单列表
  async getOrders(type) {
    const res = await request({ url: '/my/orders/all', data: { type } })
    console.log(res.data.message.orders);
    let orders = res.data.message.orders
    this.setData({
      orders:orders.map(v=>({...v,create_time_cn:(new Date(v.create_time*1000).toLocaleString())}))
    })
  }
})